<template>
    <Dialog
        :layer="layer"
        v-model:visible="layer.show"
        @close="dialogClose()"
        @confirm="submitForm()"
    >
        
        <div class="form-content">
            <el-steps
                class="steps"
                :active="step" 
                finish-status="success"
                align-center
                v-if="isEdit == 'add'"
            >
                <el-step title="站点信息填写" />
                <el-step title="选择站点模板" />
            </el-steps>
            <!-- 第一步 -->
            <el-form v-show="step == 0" label-width="120px" :rules="editFormRules" :model="editForm" ref="formRef">
                <el-form-item label="组织类型" prop="institutionType">
                    <el-radio-group
                        v-model="editForm.institutionType" 
                        size="large" 
                        :disabled="isEdit == 'edit'"
                        @change="changeInstitution"
                    >
                        <el-radio :label="2">单位</el-radio>
                        <el-radio :label="1">学校</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="组织名称" prop="typeBindId">
                    <span v-if="isEdit == 'edit'">{{editForm.institutionName}}</span>
                    <el-select
                        v-else
                        v-model="editForm.typeBindId" 
                        placeholder="请输入组织名称"
                        filterable
                        remote
                        :remote-method="basicSchoolList"
                        @change="schoolChange"
                        clearable
                    >
                        <el-option v-for="(item) in sList" 
                            :key="item.schoolId"
                            :value="item.schoolId"
                            :label="item.schoolName" 
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="组织自定义名称" prop="customName">
                    <el-input maxlength="50" v-model="editForm.customName" placeholder="请输入组织自定义名称" clearable/>
                </el-form-item>
                <el-form-item label="所在地区" prop="areaid" :class="{'editStyle':isEdit == 'edit', 'change-color':hasArea}">
                    <el-cascader 
                        style="width:100%"
                        ref="areaRef"
                        :placeholder="areaValue" 
                        v-model="editForm.areaid" 
                        :props="areaProp"
                        @change="selectArea" 
                    />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input maxlength="200" v-model="editForm.address" placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item
                    label="组织级别" 
                    prop="institutionLevel" 
                    v-show="editForm.institutionType == 2"
                    :rules="levelRule"
                 >
                    <el-select v-model="editForm.institutionLevel" placeholder="请选择组织级别" :disabled="isEdit == 'edit'">
                        <el-option v-for="(item) in institutionLevelList" 
                            :key="item.code"
                            :value="item.code"
                            :label="item.name" 
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="所属学段" 
                    prop="stages" 
                    v-show="editForm.institutionType == 1"
                    :rules="stageRule"
                 >
                    <el-select multiple v-model="editForm.stageId" placeholder="请选择所属学段" @change="setStage">
                        <el-option v-for="(item) in stageList" 
                            :key="item.code"
                            :value="item.code"
                            :label="item.name" 
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="组织属性" prop="institutionAttribute">
                    <el-select v-model="editForm.institutionAttribute" placeholder="请选择组织属性">
                        <el-option v-for="(item) in institutionAttrList" 
                            :key="item.code"
                            :value="item.code"
                            :label="item.name" 
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在空间" prop="dtTenant">
                    <el-select
                        v-model="editForm.dtTenant" 
                        placeholder="请选择所在空间"
                        filterable
                        :disabled="isEdit == 'edit'"
                    >
                        <el-option v-for="(item) in tenantList" 
                        :key="item.value"
                        :value="item.value"
                        :label="item.label" 
                    />
                    </el-select>
                </el-form-item>
            </el-form>
            <!-- 第二步 -->
            <div v-show="step == 1">
                <el-form :inline="false" label-width="120px" :model="editForm">
                    <el-form-item label="站点模板">
                        <el-radio-group v-model="editForm.templateId" size="large">
                            <el-radio
                                v-for="(item) in templateList" :key="item.id"
                                :label="item.id"
                            >{{item.showName}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <template v-slot:footer-btn>
            <el-button type="primary" v-show="step == 1 && isEdit == 'add'" @click="stepStatus(1)">上一步</el-button>
            <el-button type="primary" v-show="step == 0 && isEdit == 'add'" @click="stepStatus(0)">下一步</el-button>
        </template>
    </Dialog>

</template>

<script>
import { defineComponent, toRefs, ref, reactive, toRef, computed, onMounted, watch, nextTick } from 'vue'
import Dialog from '@/components/dialogComp.vue'
import { useAllAreaList } from '@/hooks/useAllAreaList'
import { 
    institutionList, 
    institutionAttrList, 
    institutionLevelList,
    institutionObj,
    institutionLevelObj,
    institutionAttrObj
} from '../filter-data.js'
export default defineComponent({
    // name:'',
    props: {
        isEdit: {
            type: String,
            default: 'add'
        },
        schoolList: {
            type: Array,
            default: () => []
        },
        stageList: {
            type: Array,
            default: () => []
        },
        tenantList: {
            type: Array,
            default: () => []
        },
        formData: {
            type: Object,
            default: () => {}
        },
        templateList: {
            type: Array,
            default: () => []
        }
    },
    components: {
        Dialog
    },
    setup(props, context){
        const formRef = ref(null)
        const areaRef = ref(null)
        // 状态数据
        const state = reactive({
            step: 0,
            // 地区选择框懒加载
            areaProp: {
                lazy: true,
                // checkStrictly: true,
                leaf: 'isLeaf',
                value: 'id',
                label: 'name',
                lazyLoad(node, resolve) {
                    const {value = '', level} = node
                    useAllAreaList((data = []) => {
                        resolve(data)
                    }, value)
                    
                }
            },
            institutionList,
            institutionAttrList,
            institutionLevelList,
            institutionObj,
            institutionLevelObj,
            institutionAttrObj,
            editForm: props.formData,
            layer: { // 第一步dialog
                show: false,
                title: '新建组织站点',
                okText: '保存',
                hasCancel: false,
                hasOk: false,
                width: '600px'
            },
            editFormRules: { // 校验
                institutionType: [{ required: false, message: '请选择组织类型', trigger: 'change' }],
                typeBindId: [{ required: true, message: '请输入组织名称', trigger: ['change', 'blur'] }],
                areaid: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
                address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
                institutionAttribute: [{ required: true, message: '请选择组织属性', trigger: 'change' }],
                dtTenant: [{ required: true, message: '请选择空间', trigger: 'change' }]
            },
            sList: props.schoolList || [],
            hasArea: false
        })

        // 方法
        const methods = {
            async changeInstitution(val){
                // state.editForm.typeBindId = ''
                // state.editForm.institutionName = ''
                // state.editForm.customName = ''
                methods.resetForm()
                state.hasArea = false
                state.sList = []
                await nextTick()
                let clear = ['institutionAttribute', 'typeBindId', 'institutionAttribute', 'dtTenant', 'stages']
                setTimeout(() => {
                    formRef.value.clearValidate(clear)
                }, 0);

            },
            setStage(val){
                state.editForm.stages = props.stageList.filter(item => val.includes(item.code))
            },
            async open(){
                methods.setModel(props.isEdit)
                state.layer.show = true 
                await nextTick()
                formRef.value && formRef.value.clearValidate()
            },
            async close(){
                methods.dialogClose()
                await nextTick()
                state.layer.show = false
            },
            // 新增修改显示弹窗
            setModel(type){
                const obj = {
                    title: type == 'add' ? '新建组织站点' : '编辑组织站点',
                    hasOk: type == 'edit'
                }
                state.layer = {...state.layer, ...obj}
                const { cityId = '', districtId = '', provinceId = '' } = props.formData
                if(type == 'edit'){
                    const {stages = ''} = props.formData
                    state.editForm = {
                        ...props.formData,
                        areaid: [provinceId, cityId, districtId],
                        stageId: stages[0]?.code
                    }
                }else{
                    methods.dialogClose()
                }
            },
            selectArea(val){
                let node = areaRef.value.getCheckedNodes()[0]
                console.log(node)
                const {pathLabels = [], pathValues = []} = node
                let ids = {provinceId: pathValues[0] || '', cityId: pathValues[1] || '', districtId: pathValues[2] || ''}
                let names = {provinceName: pathLabels[0] || '', cityName: pathLabels[1] || '', districtName: pathLabels[2] || ''}
                state.editForm = {...state.editForm, ...ids, ...names}
            },
            basicSchoolList(val){
                context.emit('remote-school-name', val, state.editForm.institutionType)
            },
            resetForm(){
                const notClean = ['institutionType', 'templateId']
                for (const key in state.editForm) {
                    if(!notClean.includes(key)){
                        state.editForm[key] = undefined
                    }
                }
            },
            // 弹窗关闭
            dialogClose(type){
                methods.resetForm()
                state.editForm.institutionType = 2
                state.editForm.templateId = props.templateList[0].id
                state.step = 0
                state.hasArea = false
            },
            schoolChange(val){
                let select = props.schoolList.filter(item => item.schoolId == val)
                const {
                    cityCode: cityId = '',
                    countryCode: districtId = '',
                    provinceCode: provinceId = '',
                    provinceName = '',
                    cityName = '', 
                    countryName: districtName = ''
                } = select[0]
                state.editForm.institutionName = select[0].schoolName
                state.editForm.customName = select[0].schoolName
                state.editForm.address = select[0].schoolAddress
                state.editForm.areaid = [provinceId, cityId, districtId]
                state.editForm = {...state.editForm, provinceId, cityId, districtId, provinceName, cityName, districtName}
                state.hasArea = !!((provinceName || cityName || districtName))
                // state.isEdit = hasArea ? 'edit' : 'add'
                // state.areaValue = hasArea ? [provinceName, cityName, districtName].join('/') : '请选择所在地区'
            },
            // 弹窗步骤
            stepStatus(step){
                if(step == 0){
                    formRef.value.validate((valid, fields) => {
                        if(valid){
                            state.step = 1
                            state.layer.hasOk = true
                        }
                    })
                }else{
                    state.step = 0
                    state.layer.hasOk = false
                }
            },
            // 提交表单
            submitForm(){
                if(props.isEdit == 'edit'){
                    formRef.value.validate((valid, fields) => {
                        if(valid){
                            context.emit('submit', state.editForm) 
                        }
                    })
                }else{
                    context.emit('submit', state.editForm)
                }
            }
        }
        watch(() => props.isEdit, (n) => {
            methods.setModel(n)
        })
        watch(() => props.templateList, (n) => {
            state.editForm.templateId = n[0]?.id || ''
        }, {
            deep: true
        })
        watch(() => props.schoolList, (n) => {
            state.sList = n
        }, {
            deep: true
        })
        // 计算属性
        const computes = {
            // 地区选择框默认值
            areaValue: computed(() => {
                const { provinceName = '', cityName = '', districtName = '' } = state.editForm
                return provinceName ? [provinceName, cityName, districtName].join('/') : '请选择所在地区'
            }),
            levelRule: computed(() => {
                let rule = {required: true, message: '请选择组织级别', trigger: 'change'}
                rule.required = state.editForm.institutionType == 2
                return rule
            }),
            stageRule: computed(() => {
                let rule = {required: true, message: '请选择所属学段', trigger: 'change'}
                rule.required = state.editForm.institutionType == 1
                return rule
            })
        }

        onMounted(() => {})

        return {
            ...toRefs(state),
            ...methods,
            ...computes,
            ...toRefs(props),
            formRef,
            areaRef
        }
    }
})
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    ::v-deep.editStyle,:deep.change-color{
        .el-input__inner::placeholder{
            color:#000;
        }
    }
    .steps{
        width:100%;
        margin-bottom: 20px;
    }
    .el-form-item{
        align-items: center;
    }
</style>
